<script lang="ts" setup>
import type { SettlementInfo } from '@/api/types/finance'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getSysSettlementDetails } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import { useFlow } from '@/hooks/useFlow'

definePage({
  style: {
    navigationBarTitleText: '释放定金详情',
  },
})

// 使用流程hook
const {
  currentProcess,
  getProcessInstance,
  getCurrentUserPendingTaskId,
  loading: flowLoading,
} = useFlow()

// 业务ID
const businessId = computed(() => {
  if (currentProcess.value?.businessKey) {
    return currentProcess.value.businessKey
  }
  if (currentProcess.value?.formVariables?.BUSINESS_KEY) {
    return currentProcess.value.formVariables.BUSINESS_KEY
  }
  return ''
})

// 流程ID
const flowIdValue = ref<string>('')
const idValue = ref<string>('')

// 业务详情数据
const businessDetail = ref<SettlementInfo | null>(null)
const businessLoading = ref(false)
const businessError = ref('')

// 获取流程实例信息
async function fetchProcessInfo(id: string) {
  try {
    await getProcessInstance(id)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }

    // 流程信息获取成功后，自动获取业务详情
    if (businessId.value) {
      await fetchReleaseOfDepositDetail()
    }
  }
  catch (error) {
    console.error('获取流程信息失败:', error)
    uni.showToast({
      title: '获取流程信息失败',
      icon: 'none',
    })
  }
}

// 获取释放定金详情
async function fetchReleaseOfDepositDetail() {
  if (!businessId.value) {
    return
  }

  businessLoading.value = true
  businessError.value = ''

  try {
    const res = await getSysSettlementDetails(businessId.value)
    businessDetail.value = res.data || null
  }
  catch (error) {
    console.error('获取释放定金详情失败:', error)
    businessError.value = '获取释放定金详情失败'
    uni.showToast({
      title: '获取释放定金详情失败',
      icon: 'none',
    })
  }
  finally {
    businessLoading.value = false
  }
}

// 页面加载时获取数据
onLoad((e: any) => {
  console.log('页面参数:', e)
  flowIdValue.value = e?.flowId || ''
  idValue.value = e?.id || ''
  if (!e.id) {
    uni.showToast({
      title: '没有获取到id',
      icon: 'none',
    })
    return
  }
  fetchProcessInfo(e.id)
})
</script>

<template>
  <view class="page p-4">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />

    <!-- 加载状态 -->
    <view v-if="flowLoading || businessLoading" class="flex flex-col items-center justify-center py-10">
      <view class="text-gray-500">
        加载中...
      </view>
    </view>

    <!-- 业务详情展示 -->
    <view v-else-if="businessDetail" class="space-y-4">
      <!-- 基本信息卡片 -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          定金释放基本信息
        </view>
        <view class="flex flex-col gap-y-3 text-sm">
          <view class="flex justify-between">
            <span class="text-gray-500">结算单号:</span>
            <span class="text-gray-800">{{ businessDetail.settlementNo || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">释放金额:</span>
            <span class="text-gray-800 font-medium">{{ businessDetail.amount || 0 }} 元</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">支付方式:</span>
            <span class="text-gray-800">{{ businessDetail.paymentMethod || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">支付状态:</span>
            <span class="text-gray-800">{{ businessDetail.paymentStatus || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">支付时间:</span>
            <span class="text-gray-800">{{ businessDetail.paymentTime || '-' }}</span>
          </view>
        </view>
      </view>

      <!-- 关联业务信息卡片 -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          关联业务信息
        </view>
        <view class="flex flex-col gap-y-3 text-sm">
          <view class="flex justify-between">
            <span class="text-gray-500">业务ID:</span>
            <span class="text-gray-800">{{ businessDetail.businessId || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">业务类型:</span>
            <span class="text-gray-800">{{ businessDetail.businessType || '-' }}</span>
          </view>
          <!-- 关联方信息 - 动态展示 -->
          <view v-if="businessDetail.relatedPartyInfo" class="mt-2">
            <view class="mb-2 text-sm text-gray-600">
              关联方详细信息:
            </view>
            <view v-for="(value, key) in businessDetail.relatedPartyInfo" :key="key" class="mb-1 flex justify-between">
              <span class="text-gray-500">{{ key }}:</span>
              <span class="text-gray-800">{{ typeof value === 'object' ? JSON.stringify(value) : value || '-' }}</span>
            </view>
          </view>
        </view>
      </view>

      <!-- 时间信息卡片 -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          时间信息
        </view>
        <view class="text-sm space-y-3">
          <view class="flex justify-between">
            <span class="text-gray-500">创建时间:</span>
            <span class="text-gray-800">{{ businessDetail.createTime || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">更新时间:</span>
            <span class="text-gray-800">{{ businessDetail.updateTime || '-' }}</span>
          </view>
        </view>
      </view>

      <!-- 流程信息卡片 -->
      <view class="border border-gray-100 rounded-lg bg-white p-4 shadow-md">
        <view class="mb-3 border-b border-gray-100 pb-2 text-lg text-gray-800 font-medium">
          流程信息
        </view>
        <view v-if="currentProcess" class="flex flex-col gap-y-3 text-sm">
          <view class="flex justify-between">
            <span class="text-gray-500">流程名称:</span>
            <span class="text-gray-800">{{ currentProcess.name || '-' }}</span>
          </view>
          <view class="flex justify-between">
            <span class="text-gray-500">流程状态:</span>
            <span class="text-gray-800">{{ currentProcess.status === 1 ? '进行中' : '已结束' }}</span>
          </view>
        </view>
        <view v-else class="py-2 text-center text-gray-500">
          暂无流程信息
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="businessError" class="py-10 text-center text-gray-500">
      {{ businessError }}
      <button class="mt-3 text-blue-500" @click="fetchProcessInfo">
        重新获取
      </button>
    </view>

    <!-- 无数据状态 -->
    <view v-else class="py-10 text-center text-gray-500">
      暂无业务信息
    </view>

    <!-- 审批操作栏组件 -->
    <ApprovalActionBar
      v-if="flowIdValue && currentProcess?.status === 1"
      :process-id="flowIdValue"
    />
  </view>
</template>

<style lang="scss" scoped>
// 页面样式
.page {
  padding-bottom: 80px; // 为底部操作栏留出空间
}
</style>
